package com.android.plc.engine;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

public class Command implements Parcelable
{
	private static final String TAG = "Command";
	public static final int STX_CODE = 0x02;
	public static final int ETX_CODE = 0x03;

	public int STX;
	public int LENGTH;
	public int USER_CODE;
	public int HOME_UNIT;
	public int COMMAND;
	public int DATA1;
	public int DATA2;
	public int ETX;
	public int CHECKSUM;
	public boolean R_ITSELF = true;

	public Command()
	{
	}

	@Override
	public String toString()
	{
		return String.format("%02x %02x %02x %02x %02x %02x %02x %02x %02x", STX, LENGTH, USER_CODE, HOME_UNIT,
				COMMAND, DATA1, DATA2, ETX, CHECKSUM);
	}

	public void sent(DataOutputStream out) throws IOException
	{
		out.write(STX);
		out.write(LENGTH);
		out.write(USER_CODE);
		out.write(HOME_UNIT);
		out.write(COMMAND);
		out.write(DATA1);
		out.write(DATA2);
		out.write(ETX);
		out.flush();
	}

	public boolean isAvailable()
	{
		int sum = STX + LENGTH + USER_CODE + HOME_UNIT + COMMAND + DATA1 + DATA2 + ETX;
		Log.d(TAG, " sum = " + sum);
		sum = (sum ^ 0x00FF) + 1;
		Log.d(TAG, " ~sum = " + sum + " CHECKSUM = " + CHECKSUM);
		return sum == CHECKSUM;
	}

	public static Command receive(DataInputStream din) throws IOException
	{
		Command sc = null;
		int stx = -1;
		Log.d(TAG, "rev socket read start");
		if ((stx = din.read()) == STX_CODE)
		{
			sc = new Command();
			sc.STX = stx;
			sc.LENGTH = din.read();
			sc.USER_CODE = din.read();
			sc.HOME_UNIT = din.read();
			sc.COMMAND = din.read();
			sc.DATA1 = din.read();
			sc.DATA2 = din.read();
			sc.ETX = din.read();
			sc.R_ITSELF = (sc.ETX & 0x10) != 0;
			sc.CHECKSUM = din.read();
			din.skip(din.available());
		}
		return sc;
	}

	public int describeContents()
	{
		return 0;
	}

	public void writeToParcel(Parcel out, int flags)
	{
		out.writeInt(STX);
		out.writeInt(LENGTH);
		out.writeInt(USER_CODE);
		out.writeInt(HOME_UNIT);
		out.writeInt(COMMAND);
		out.writeInt(DATA1);
		out.writeInt(DATA2);
		out.writeInt(ETX);
	}

	public static final Parcelable.Creator<Command> CREATOR = new Parcelable.Creator<Command>()
	{
		public Command createFromParcel(Parcel in)
		{
			return new Command(in);
		}

		public Command[] newArray(int size)
		{
			return new Command[size];
		}
	};

	private Command(Parcel in)
	{
		STX = in.readInt();
		LENGTH = in.readInt();
		USER_CODE = in.readInt();
		HOME_UNIT = in.readInt();
		COMMAND = in.readInt();
		DATA1 = in.readInt();
		DATA2 = in.readInt();
		ETX = in.readInt();
		R_ITSELF = (ETX & 0x10) != 0;
		CHECKSUM = in.readInt();
	}

}
